package com.mynetwork.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mynetwork.activity.MainActivity;
import com.mynetwork.utils.Size;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class NetworkManager {
	public static final String TAG = "NetworkManager";
	
	public static String SERVER_REAL_URL_API = "http://14.63.225.123:8080/wanted_api/";
	public static String SERVER_TEST_URL_API = "http://14.63.225.123:8080/wanted_api/";
	
	//서버 문자열
	public final static String SERVER_STR_MARKET_GOOGLE = "GOOGLE";
	public final static String SERVER_STR_MARKET_OLLEH = "OLLEH";
	
	public static String APP_UNIQUE_NUMBER = "API/v1_0/appUniqueNo?";
	
	public static String GCM_REGISTER = "API/v1_0/gcm/on?";
	public static String PRODUCT_LIST = "API/v1_0/products/all?";
	public static String CONTENT_INFO_LIST = "API/v1_0/conts?";
	public static String BANNER_INFO_LIST = "API/v1_0/ad/banner?";
	public static String NEWS_INFO_LIST = "API/v1_0/notice/main?";
	
	
	public static String ORDER_UPLOAD = "API/v1_0/estimateUpload?";
	public static String ORDER_SEARCH = "API/v1_0/estimateList?";

	public static String STATISTICS_UPLOAD = "API/v1_0/logUpload2?";
	
	public static int listCount = 0;

	public static String getApiServerURL() {
		if(Config.isRealServer)
			return SERVER_REAL_URL_API;
		return SERVER_TEST_URL_API;
	}

//	public static String getLogServerURL() {
//		if(Config.isRealServer)
//			return SERVER_REAL_URL_LOG;
//		return SERVER_TEST_URL_LOG;
//	}
//	
//	public static String getDoServerURL() {
//		if(Config.isRealServer)
//			return SERVER_REAL_URL_DO;
//		return SERVER_TEST_URL_DO;
//	}
	
	public static String getStoreType() {
		if(Config.isMarketGoogle)
			return SERVER_STR_MARKET_GOOGLE;
		return SERVER_STR_MARKET_OLLEH;
	}
	
	public static HttpURLConnection getUrlConnection(String urlstr) throws IOException {
		HttpURLConnection conn;
		URL url = new URL(urlstr);
		conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(2000);
		conn.setAllowUserInteraction(true);
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		conn.addRequestProperty("Accept", "application/json");
		return conn;
	}
	public static HttpURLConnection getUrlGZIPConnection(String urlstr) throws IOException {
		HttpURLConnection conn;
		URL url = new URL(urlstr);
		conn = (HttpURLConnection) url.openConnection();
		
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(2000);
		conn.setAllowUserInteraction(true);
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		conn.addRequestProperty("Content-Encoding", "gzip");
		conn.addRequestProperty("Accept", "application/json");
		return conn;
	}
	public static StringBuilder getNetworkDefaultPacket() {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("lat=" + MainActivity.lat );
		strBuilder.append("&lng=" + MainActivity.lng );
		strBuilder.append("&listCount=" + listCount);
		strBuilder.append("&userIdx=" + "1" );
		if (AppData.APP_ID != null){
			strBuilder.append("&device_id=" + AppData.APP_ID);
		}
		else{
			strBuilder.append("&device_id=" + AppData.MAC_ADDRESS);
		}
		strBuilder.append("&model=" + AppData.DEVICE_MODEL);
		strBuilder.append("&os_ver=" + AppData.OS_VERSION);
		strBuilder.append("&lcd_size=" + Size.DisplayWidth + "x" + Size.DisplayHeight);
		strBuilder.append("&store_type=" + getStoreType());
		strBuilder.append("&app_id=" + AppData.APP_PACK_NAME);
		strBuilder.append("&app_ver=" + AppData.APP_VERSION);
		return strBuilder;
	}
	
	public void download(Context context,OnNetworkListener l) {
		mOnNetworkListener = l;
		new DownloadAsyncTask().execute();
	}
	
	protected long mUpdateTimeStamp;
	protected boolean sIsUpdate = false;
	public OnNetworkListener mOnNetworkListener;
    public class DownloadAsyncTask extends AsyncTask<Object, Object, Boolean> {
		@Override
		protected Boolean doInBackground(Object... params) {
			HttpURLConnection conn = null;
			try {
				
				conn = getConnection();
	            InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");  
	            BufferedReader reader = new BufferedReader(tmp); 
	            StringBuilder builder = new StringBuilder(); 
	            String str; 
	            while ((str = reader.readLine()) != null) {       // 서버에서 라인단위로 보내줄 것이므로 라인단위로 읽는다 
	                builder.append(str + "\n");                     // View에 표시하기 위해 라인 구분자 추가 
	            } 
	            tmp.close();
	            
				JSONObject jsonObj = new JSONObject(builder.toString());
				
				if (jsonObj.getInt("returnCode") != 0)
					return false;

				try {
					mUpdateTimeStamp = jsonObj.getLong("datetime");
				} catch (Exception e) {
					
				}
				return jsonParser(jsonObj);

			} catch (SocketTimeoutException e) {
 				Log.e(TAG,"Error : SocketTimeoutException");
 				return false;
 			} catch (ConnectTimeoutException e) {
 				Log.e(TAG,"Error : ConnectTimeoutException");
 				return false;
 			} catch (Exception e) {
 				Log.e(TAG,"" + e);
				if(conn != null){
					conn.disconnect();
					conn = null;
				}
				return false;
			}
 		}
 		
 		@Override
 		protected void onPostExecute(Boolean result) {
 			if (mOnNetworkListener != null) {
 				if (result) {
 					loadSuccess();
 					mOnNetworkListener.onSuccess(NetworkManager.this);
 				} else {
 					getLocalData();
 					loadFailed();
 					mOnNetworkListener.onError(NetworkManager.this);
 				}
 			}
 		}
    }
    
    public HttpURLConnection getConnection() throws IOException {
    	return null;
    }
    
    public boolean jsonParser(JSONObject jsonObj) throws JSONException {
    	return false;
    }
    
    public void getLocalData(){
    }
    
    public void loadSuccess() {};
    public void loadFailed() {};
    
    
}
